var util = require('../../utils/util')
Page({
  data: {
    addressLoading: false,
    chooseAddress: false,
    //招商中心状态， 0-未实名 1-已实名
    CBOapplied: 0,
    menuArr: [{
        title: '推荐商家',
        url: '/pages/CBOpages/store/store'
      },
      {
        title: '我的收益',
        url: '/pages/CBOpages/earn/earn'
      },
      {
        title: '提现记录',
        url: '/pages/CBOpages/histry/histry'
      },
    ],
    fieldArr: [{
        id: 0,
        value: '',
        label: '您的姓名',
        placeholder: '请输入您的姓名',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '10',
        errorMessage: '请输入您的姓名',
        error: false,
        disabled: false,
      },
      {
        id: 1,
        value: '',
        label: '身份证号',
        placeholder: '请输入您的身份证号',
        type: 'idcard',
        isLink: false,
        border: true,
        maxlength: '18',
        errorMessage: '请输入您的身份证号',
        error: false,
        disabled: false,
      },
      {
        id: 2,
        value: '',
        label: '联系电话',
        placeholder: '请输入您的联系电话',
        type: 'number',
        isLink: false,
        border: true,
        maxlength: '11',
        errorMessage: '请输入您的联系电话',
        error: false,
        disabled: false,
      },
      {
        id: 3,
        value: '',
        text: '',
        label: '联系地址',
        placeholder: '请选择您的省市县',
        type: 'text',
        isLink: true,
        border: false,
        maxlength: '40',
        errorMessage: '请选择您的省市县',
        error: false,
        disabled: true,
      },
      {
        id: 4,
        value: '',
        label: ' ',
        placeholder: '请输入您的详细地址',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '40',
        errorMessage: '请输入您的详细地址',
        error: false,
        disabled: false,
      },
    ],
    AddressColumns: [{
        values: [],
        className: '省',
      },
      {
        values: [],
        className: '市',
      },
      {
        values: [],
        className: '县',
      },
    ]
  },
  onClose() {
    this.setData({
      chooseAddress: false
    })
  },
  fieldBlur(e) {
    // console.log(e)
    let i = e.currentTarget.dataset.index;
    let value = e.detail.value;
    let cursor = e.detail.cursor;
    this.setData({
      [`fieldArr[${i}].error`]: cursor === 0,
      [`fieldArr[${i}].value`]: value,
    })
  },
  fieldFocus(e) {
    let i = e.currentTarget.dataset.index;
    this.setData({
      [`fieldArr[${i}].error`]: false,
    })
  },
  reApply() {
    //重新申请，设置applyStatus为0
    this.setData({
      applyStatus: 0
    })
  },
  addressOnChoosen(e) {
    //选择地址时，根据选中的选项发送请求
    // console.log(e)
    var index = e.detail.index;
    var code = e.detail.value[index].code
    // console.log(index, code);
    if (index <= 1) {
      this.setData({
        'addressLoading': true
      })
      //当修改的是省级/市级选项时，需要刷新下级菜单
      //获取下级菜单
      let url = index === 0 ? ('get/city?code=' + code) : ('get/area?code=' + code)
      util.sendRequest(url, 'GET').then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          let result = res.data.result
          this.setData({
            [`AddressColumns[${index+1}].values`]: result,
          })
          //修改的是省级菜单，那么还要获取再下一级菜单
          if (index === 0) {
            var code2 = result[0].code;
            // console.log(code2)
            util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
              if (res.data.code === 0) {
                let result = res.data.result;
                this.setData({
                  [`AddressColumns[2].values`]: result,
                  addressLoading: false,
                })
              }
            })
          } else {
            this.setData({
              'addressLoading': false
            })
          }
        }
      })
    }
  },

  addressConfirm(e) {
    // console.log(e.detail)
    let str = e.detail.value[0].name + e.detail.value[1].name + e.detail.value[2].name
    this.setData({
      'fieldArr[3].value': e.detail,
      'fieldArr[3].text': str,
    })
    this.onClose();
  },

  navPage(e) {
    // console.log(e.currentTarget.dataset.url)
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url,
    })
  },

  fieldTap(e) {
    let id = e.currentTarget.dataset.value;
    if (id == 3) {
      //弹出地址选择框
      this.setData({
        chooseAddress: true
      })
      //获取默认显示的省市县信息，请求完成前显示加载画面
      this.setData({
        addressLoading: true
      })
      util.sendRequest('get/province', 'GET').then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          let result = res.data.result;
          this.setData({
            [`AddressColumns[0].values`]: result,
            addressLoading: false,
          })
          var code1 = result[0].code
          util.sendRequest('get/city?code=' + code1, 'GET').then(res => {
            // console.log(res)
            if (res.data.code === 0) {
              let result = res.data.result;
              this.setData({
                [`AddressColumns[1].values`]: result,
              })
              var code2 = result[0].code;
              util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
                if (res.data.code === 0) {
                  let result = res.data.result;
                  this.setData({
                    [`AddressColumns[2].values`]: result,
                    addressLoading: false,
                  })
                }
              })
            }
          })
        }
      })
    }
  },
  apply() {
    //简单校验，然后向后台申请实名校验并保存信息， 成功会切换状态信息， 失败弹出提示
    var fieldArr = this.data.fieldArr;
    var num = 0;
    for (let i in fieldArr) {
      if (fieldArr[i].value) {
        num++
      } else {
        this.setData({
          [`fieldArr[${i}].error`]: true
        })
        wx.showToast({
          title: fieldArr[i].errorMessage,
          icon: 'none'
        })
        break;
      }
    }
    // apply/merchant
    //成功 切换信息
    // console.log(fieldArr)
    if (num === 5) {
      //提交申请
      let data = {
        name: fieldArr[0].value,
        id_card_no: fieldArr[1].value,
        phone: fieldArr[2].value,
        province: fieldArr[3].value.value[0].name,
        city: fieldArr[3].value.value[1].name,
        area: fieldArr[3].value.value[2].name,
        detail_address: fieldArr[4].value,
      }
      util.sendRequest('apply/merchant', 'POST', data).then(res => {
        if (res.data.code === 0) {
          this.getUserInfo()
          wx.showToast({
            title: '提交成功！请等待审核。',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: res.data.code,
            icon: 'none'
          })
        }
      })
    }
  },
  getUserInfo() {
    util.sendRequest('get/userinfo', 'GET').then(res => {
      if (res.data.code === 0) {
        var result = res.data.result
        this.setData({
          userInfo: result,
          isMerchant: result.is_merchant === 1 ? true : false
        })
        //如果用户未实名，则弹出提示
        if (result.is_merchant === 2) {
          //查看是否提交过请求
          util.sendRequest('merchant/audit/state', 'GET').then(res => {
            if (res.data.code === 0) {
              let result = res.data.result;
              // console.log(result)
              this.setData({
                'applyStatus': result.audit_state
              })
              if (result.audit_state === 0) {
                wx.showToast({
                  title: '请先填写实名信息',
                  icon: 'none',
                  duration: 2000,
                })
              }
            }
          })
        } else {
          //已经是招商员，获取收益信息
          /********/
          this.setData({
            'userInfo.create_time': this.data.userInfo.create_time.slice(0, 10)
          })
        }
      }
    })
  },

  onLoad: function (options) {
    this.setData({
      navHeight: getApp().globalData.navHeight,
      hoverHeightNotab: getApp().globalData.hoverHeightNotab,
    })
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})